package com.wq.httpclientcore.client;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wq.httpclientcore.constants.CacheConstants;
import com.wq.httpclientcore.entities.po.ApiConfig;
import com.wq.httpclientcore.service.ApiConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisDataInitializer implements CommandLineRunner {

    @Autowired
    private ApiConfigService apiConfigService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void run(String... args) {
        log.info("RedisDataInitializer run");
        LambdaQueryWrapper<ApiConfig> apiConfigLambdaQueryWrapper = Wrappers.lambdaQuery(ApiConfig.class);
        apiConfigLambdaQueryWrapper.eq(ApiConfig::getEnabled, true);
        List<ApiConfig> apiConfigList = apiConfigService.list(apiConfigLambdaQueryWrapper);

        if (apiConfigList != null && !apiConfigList.isEmpty()) {
            for (ApiConfig apiConfig : apiConfigList) {
                String key = CacheConstants.API_CONFIG_PREFIX + apiConfig.getId();
                redisTemplate.opsForValue().set(key, apiConfig, CacheConstants.API_CONFIG_EXPIRE_MINUTES, TimeUnit.MINUTES);
            }
        }
    }
}